package com.jincp.common.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.jincp.common.base.BaseApplication;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @updator thanatosx
 */
public class TDevice {

    private static Context context;

    static {
        context = BaseApplication.getInstance();
    }

    public static boolean isExistSDCard() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static boolean isPortrait() {
        return context.getResources().getConfiguration()
                .orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    public static String getManufacture(Context context) {
        return Build.MANUFACTURER;
    }

    public static void callPhone(Activity activity, String mobile) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mobile));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    /**
     * 打开或关闭键盘
     */
    public static void startOrCloseKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        // 得到InputMethodManager的实例
        if (imm.isActive()) {
            // 如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public static void closeKeyboard(EditText view) {
        view.clearFocus();
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    public static void openKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }


    /**
     * 打开浏览器
     *
     * @param context
     * @param url
     */
    public static void openBrowser(Context context, String url) {
        if (TextUtils.isEmpty(url)) return;
        try {
            //启用外部浏览器
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.getInstance().show("无法浏览此网页");
        }
    }


    /**
     * 平板电脑?
     *
     * @return ??
     */
    public static boolean isTablet() {
        int s = context.getResources().getConfiguration().screenLayout;
        s &= Configuration.SCREENLAYOUT_SIZE_MASK;
        return s >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public static boolean hideSoftKeyboard(View view) {
        if (view == null) return false;
        View mFocusView = view;

        Context context = view.getContext();
        if (context != null && context instanceof Activity) {
            Activity activity = ((Activity) context);
            mFocusView = activity.getCurrentFocus();
        }
        if (mFocusView == null) return false;
        mFocusView.clearFocus();
        InputMethodManager manager = (InputMethodManager) mFocusView.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        return manager.hideSoftInputFromWindow(mFocusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void showSoftKeyboard(View view) {
        if (view == null) return;
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        if (!view.isFocused()) view.requestFocus();

        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view, 0);
    }

    public static boolean isHaveMarket(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_APP_MARKET);
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> infos = pm.queryIntentActivities(intent, 0);
        return infos.size() > 0;
    }

    public static void openAppInMarket(Context context) {
        if (context == null) return;
        if (!isHaveMarket(context)) {
            ToastUtil.getInstance().show("你手机中没有安装应用市场！");
            return;
        }
        String pckName = context.getPackageName();
        gotoMarket(context, pckName);
    }

    public static void gotoMarket(Context context, String pck) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("market://details?id=" + pck));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

    public static void installAPK(Context context, File file) {
        if (file == null || !file.exists())
            return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri apkUri = AppUtils.getFileUri(context, file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static boolean openAppActivity(Context context,
                                          String packageName,
                                          String activityName) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ComponentName cn = new ComponentName(packageName, activityName);
        intent.setComponent(cn);
        try {
            context.startActivity(intent);
            return true;
        } catch (ActivityNotFoundException e) {
            return false;
        }
    }

    public static boolean isWifiOpen() {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null) return false;
        if (!info.isAvailable() || !info.isConnected()) return false;
        if (info.getType() != ConnectivityManager.TYPE_WIFI) return false;
        return true;
    }

    @SuppressWarnings("deprecation")
    public static void copyTextToBoard(String string) {
        if (TextUtils.isEmpty(string)) return;
        ClipboardManager clip = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clip.setText(string);
        ToastUtil.getInstance().show("复制到剪贴板");
    }

    /**
     * 调用系统安装了的应用分享
     *
     * @param context
     * @param title
     * @param url
     */
    public static void showSystemShareOption(Activity context,
                                             final String title, final String url) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享：" + title);
        intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
        context.startActivity(Intent.createChooser(intent, "选择分享"));
    }

    /**
     * 判断是否安装了application
     *
     * @param context
     * @param packageName 项目的packageName
     */
    public static boolean isInstallByPackageName(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (packageInfoList != null) {
            for (PackageInfo packageInfo : packageInfoList) {
                if (TextUtils.equals(packageName, packageInfo.packageName)) ;
                return true;
            }
        }
        return false;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    public static final boolean isGPSOpen(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    public static  String getPhoneInfo() {
        StringBuilder stringBuild = new StringBuilder();
        stringBuild.append("android.os.Build.MODEL：");
        stringBuild.append(android.os.Build.MODEL);// 手机型号
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.BRAND：");
        stringBuild.append(android.os.Build.BRAND);//手机品牌
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.PRODUCT：");
        stringBuild.append(android.os.Build.PRODUCT);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.CPU_ABI：");
        stringBuild.append(android.os.Build.CPU_ABI);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.TAGS：");
        stringBuild.append(android.os.Build.TAGS);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.VERSION_CODES.BASE：");
        stringBuild.append(android.os.Build.VERSION_CODES.BASE);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.VERSION.SDK：");
        stringBuild.append(android.os.Build.VERSION.SDK);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.VERSION.RELEASE：");
        stringBuild.append(android.os.Build.VERSION.RELEASE);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.DEVICE：");
        stringBuild.append(android.os.Build.DEVICE);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.DISPLAY：");
        stringBuild.append(android.os.Build.DISPLAY);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.FINGERPRINT：");
        stringBuild.append(android.os.Build.FINGERPRINT);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.ID：");
        stringBuild.append(android.os.Build.ID);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.MANUFACTURER：");
        stringBuild.append(android.os.Build.MANUFACTURER);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.USER：");
        stringBuild.append(android.os.Build.USER);
        return stringBuild.toString();

    }
}
